package com.lvtulife.paas.gtd.service.impl;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.lvtulife.paas.gtd.entity.GtdIdeal;
import com.lvtulife.paas.gtd.service.GtdIdealOplogServiceI;
import com.lvtulife.paas.gtd.service.GtdIdealServiceI;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.lvtulife.paas.gtd.mapper.GtdIdealAdjustMapper;
import com.lvtulife.paas.gtd.entity.GtdIdealAdjust;
import com.lvtulife.paas.gtd.service.GtdIdealAdjustServiceI;
import com.lvtulife.common.service.impl.BaseServiceImpl;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.text.MessageFormat;
import java.util.Date;
import java.util.List;

/**
 * GtdIdealAdjust 表数据服务层接口实现类
 */
@Service
@Transactional(readOnly = true)
public class GtdIdealAdjustServiceImpl extends BaseServiceImpl<GtdIdealAdjustMapper, GtdIdealAdjust> implements GtdIdealAdjustServiceI {

    @Autowired
    private GtdIdealServiceI idealService;

    @Autowired
    private GtdIdealOplogServiceI oplogService;

    @Override
    @Transactional(readOnly = false, propagation = Propagation.REQUIRED)
    public Long saveAdjust(Long idealId, String cause, String content) {
        verifyParams(idealId, cause, content);

        checkIdeal(idealId);

        GtdIdealAdjust entity = new GtdIdealAdjust();
        entity.setLid(idealId);
        entity.setCause(cause);
        entity.setContent(content);
        entity.setSumDt(new Date());

        int count = baseMapper.insert(entity);
        checkOperation(count);

        oplogService.saveOplog(idealId, MessageFormat.format("内容调整为:{0}", content));

        return entity.getId();
    }


    @Override
    @Transactional(readOnly = false, propagation = Propagation.REQUIRED)
    public void delAdjust(Long adjustId) {
        verifyEntity(new GtdIdealAdjust(adjustId));

        deleteById(adjustId);
    }

    @Override
    @Transactional(readOnly = false, propagation = Propagation.REQUIRED)
    public void clearIdealAdjust(Long idealId) {
        checkIdeal(idealId);

        GtdIdealAdjust entity = new GtdIdealAdjust();
        entity.setLid(idealId);
        deleteSelective(entity);
    }

    @Override
    public List<GtdIdealAdjust> findAdjusts(Long idealId) {
        EntityWrapper<GtdIdealAdjust> wrapper = new EntityWrapper<>();
        wrapper.where("lid={0}", idealId);
        wrapper.orderBy("sumDt", false);
        return selectList(wrapper);
    }

    /* 校验理想对象是否存在 */
    private void checkIdeal(Long idealId) {
        idealService.verifyEntity(new GtdIdeal(idealId));
    }
}